﻿#include "acceptor.h"
#include "channel.h"
#include "eventloop.h"
#include "log.h"

Acceptor::Acceptor(EventLoop *eloop, uint16_t port, const std::string& ip)
    : m_eloop(eloop)
    , m_socket(createServer(port, ip))
    , m_listenChannel(new Channel(eloop, m_socket.fd()))
{
    m_listenChannel->setReadCallback(std::bind(&Acceptor::handleRead, this));
}

Acceptor::~Acceptor()
{
    m_listenChannel->remove();
    m_socket.close();
}

void Acceptor::listen()
{
    m_listenChannel->enableRead();
}

int Acceptor::createServer(uint16_t port, const std::string& ip)
{
    bool ret = m_socket.createTcpServer(port, ip);
    if(ret == false)
    {
        LOG(Fatal, "Create server socket failed");
        abort();
    }
    return m_socket.fd();
}

void Acceptor::handleRead()
{
    int connfd = m_socket.accept();
    if(connfd < 0)
    {
        LOG(Warning, "Acceptor accept failed");
        return;
    }
    if(m_acceptCb)
    {
        m_acceptCb(connfd);
    }
}

void Acceptor::setNewConnectionCallback(AcceptCallBack callback)
{
    m_acceptCb = callback;
}



